<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // 实现一个深拷贝
      //使用递归遍历
      const origin = {
        name: '张三',
        age: '18',
        like() {
          console.log('喜欢唱歌、滑冰');
        },
        book: { name: '把妹达人', price: 22 },
      };

      //...只能拷贝第一层对象,第二层对象还是浅拷贝
      //   let obj22 = { ...origin };
      //   obj22.book.name = '防狼防渣男';
      //   console.log(origin); //原对象变了

      let DeepCopy = (obj) => {
        let newObj = {};
        for (let attr in obj) {
          //attr:对象的属性名 ,例如name,age,link,book
          //obj[attr]:对象的属性值,例如张三,18

          if (typeof obj[attr] == 'object') {
            newObj[attr] = DeepCopy(obj[attr]);
          } else {
            newObj[attr] = obj[attr];
          }
        }
        return newObj;
      };

      let res = DeepCopy(origin);
      res.book.name = '哈喽我是更改后的值';
      console.log(res);
      console.log(origin);
    </script>
  </body>
</html>
